package net.googlecode.kharchenko.controllers;

import net.googlecode.kharchenko.domains.Person;
import net.googlecode.kharchenko.services.PersonService;
import net.googlecode.kharchenko.services.SecurityService;
import net.googlecode.kharchenko.validation.RegistrationValidation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * Controller of registration page.
 */
@Controller
@RequestMapping("/register")
public class RegistrationController {

    @Autowired
    private RegistrationValidation registrationValidation;
    @Autowired
    private PersonService personService;
    @Autowired
    private SecurityService securityService;


    protected static final Logger logger = Logger.getLogger(RegistrationController.class);

    @RequestMapping(method = RequestMethod.GET)
    public String showRegistration(Map model, HttpServletRequest request) {
        logger.debug("Check if the user is guest");
        if (!securityService.getCurrentUser().equals("guest")) {

            logger.info("Redirecting to home");
            return "redirect:home";
        }
        logger.info("Create object Person");
        Person prs = new Person();
        logger.info("Set parametres that send to view");
        model.put("person", prs);
        model.put("groupList", personService.getAllGroups());
        logger.info("Show registration page");
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processRegistration(HttpServletRequest request, Person person,
                                      BindingResult result, Map model) {


        logger.info("Validate input information");
        registrationValidation.validateRegForm(person, result);
        if (result.hasErrors()) {

            model.put("groupList", personService.getAllGroups());
            return "register";
        }
        Long groupId = person.getGroup().getId();
        String groupName = personService.getGroup(groupId).getName();
        person.getGroup().setName(groupName);
        logger.debug("Save  person to database");
        personService.savePerson(person);
        logger.info("Return sucess register view");
        return "registersuccess";
    }

}
